package fs.cypher {
	import flash.utils.Dictionary;
	/**
	 * ...
	 * @author flyingSnow
	 */
	public class Vigenere {
		
		public static function encrypt(plainText:String,key:String,cypherTable:String):String {
			var arrKeys:Array = [];
			var dicChar2Index:Dictionary = new Dictionary();
			var i:int = 0;
			
			//反查字典
			for (i = 0; i < cypherTable.length; i++ ) {
				dicChar2Index[cypherTable.charAt(i)] = i;
			}
			
			//密钥数组
			for (i = 0; i < key.length; i++ ) {
				arrKeys.push(dicChar2Index[key.charAt(i)]);
			}
			
			var tableSize:int = cypherTable.length;
			var keyLength:int = key.length;
			var arrCypher:Array = [];
			
			for (i = 0; i < plainText.length; i++ ) {
				var orgnChar:String = plainText.charAt(i);
				var orgnIndex:int = dicChar2Index[orgnChar];
				
				var keyChar:String = key.charAt(i % keyLength);
				var keyCharIndex:int = dicChar2Index[keyChar];
				
				var cypherCharIndex:int = (orgnIndex + keyCharIndex) % tableSize;
				var cypherChar:String = cypherTable.charAt(cypherCharIndex);
				
				arrCypher.push(cypherChar);
			}
			return arrCypher.join("");
		}
		
		public static function decrypt(cypherText:String, key:String, cypherTable:String):String {
			var arrKeys:Array = [];
			var dicChar2Index:Dictionary = new Dictionary();
			var i:int = 0;
			
			//反查字典
			for (i = 0; i < cypherTable.length; i++ ) {
				dicChar2Index[cypherTable.charAt(i)] = i;
			}
			
			//密钥数组
			for (i = 0; i < key.length; i++ ) {
				arrKeys.push(dicChar2Index[key.charAt(i)]);
			}
			
			var tableSize:int = cypherTable.length;
			var keyLength:int = key.length;
			var arrPlain:Array = [];
			
			for (i = 0; i < cypherText.length; i++ ) {
				var orgnChar:String = cypherText.charAt(i);
				var orgnIndex:int = dicChar2Index[orgnChar];
				
				var keyChar:String = key.charAt(i % keyLength);
				var keyCharIndex:int = dicChar2Index[keyChar];
				
				var plainCharIndex:int = (orgnIndex - keyCharIndex + tableSize) % tableSize;
				var plainChar:String = cypherTable.charAt(plainCharIndex);
				
				arrPlain.push(plainChar);
			}
			return arrPlain.join("");
		}
		
	}

}